package com.bzyd.verify.imagecode;

import com.bzyd.verify.common.SysResult;
import com.bzyd.verify.utils.CookieUtil;
import com.bzyd.verify.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
public class ImageCodeController {

    @Autowired
    private ImageCodeProperties imageCodeProperties;

    @RequestMapping("/getImageVerifyCode")
    public void getImageVerifyCode(HttpServletResponse response) throws Exception {
        ImageCodeGenerator imageCodeGenerator = new ImageCodeGenerator(imageCodeProperties);
        String code = imageCodeGenerator.getRandomCode(response);
        log.info("图形验证码：{}",code);
    }

    //注意：校验验证码逻辑要写在业务接口里面
    @RequestMapping("/testCheckImageCode")
    public SysResult testCheckImageCode(String code, String key, HttpServletRequest request){
        if (StringUtils.isBlank(code)){
            return SysResult.fail("验证码不能为空！");
        }

        if (StringUtils.isBlank(key)){
            key = CookieUtil.getCookieValueByName(request,"verid");
        }

        String redisCode = RedisUtil.get(key);
        if (StringUtils.isBlank(redisCode)){
            return SysResult.fail("验证码过期！");
        }

        if (code.toLowerCase().equals(redisCode.toLowerCase())){
            return SysResult.ok("验证码正确！");
        }
        else {
            return SysResult.fail("验证码错误！");
        }

    }
}
